<template>
  <div class="edit-profile-container">
    <NavBar>
      <template #default> 编辑资料 </template>
    </NavBar>

    <div class="edit-content">
      <!-- 头像编辑区域 -->
      <div class="avatar-edit-section">
        <div class="avatar-preview">
          <!-- 如果有头像URL，显示头像图片 -->
          <img
            v-if="formData.avatar"
            :src="formData.avatar"
            alt="用户头像"
            class="user-avatar"
          />
          <!-- 否则显示默认图标 -->
          <el-icon v-else class="user-avatar-placeholder">
            <User />
          </el-icon>
        </div>
        <!-- Element Plus 的上传组件，用于选择新头像 -->
        <el-upload
          class="avatar-uploader"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleAvatarChange"
        >
          <template #trigger>
            <el-button size="small" type="primary">更换头像</el-button>
          </template>
        </el-upload>
      </div>

      <!-- 用户信息表单 -->
      <el-form ref="editForm" :model="formData" label-width="80px">
        <el-form-item label="账号">
          <!-- 账号不可编辑 -->
          <el-input v-model="formData.userName" disabled />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="formData.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
            <el-radio :label="0">保密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="formData.mobile" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="formData.email" />
        </el-form-item>
      </el-form>

      <!-- 保存按钮 -->
      <el-button type="primary" @click="submitForm">保存</el-button>
    </div>
  </div>
</template>

<script setup>
import NavBar from "../../components/common/NavBar.vue";
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useUserStore } from "@/stores/user";
import { useRouter, onBeforeRouteLeave } from "vue-router";
import { User } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 导入 updateUser 方法
import { updateUser } from "@/api/UserApi";

const userStore = useUserStore();
const router = useRouter();
const editForm = ref(null);
const formData = ref({
  userId: null,
  userName: "",
  gender: null,
  mobile: "",
  email: "",
  avatar: "", // 当前头像 URL
  avatarFile: null, // 待上传的头像文件
});

// 存储初始表单数据，用于比较是否有修改
const originalFormData = ref({});
// 存储创建的头像预览 URL 引用，用于内存清理
const avatarObjectURL = ref(null);

onMounted(() => {
  // 从 userStore 中获取当前用户信息并填充到 formData
  if (userStore.userInfo) {
    // 标准化初始数据，确保字段都有合适的默认值
    const userData = {
      ...userStore.userInfo,
      gender: userStore.userInfo.gender ?? null,
      mobile: userStore.userInfo.mobile || '',
      email: userStore.userInfo.email || '',
      avatar: userStore.userInfo.avatar || '',
      avatarFile: null
    };

    formData.value = userData;
    // 深拷贝保存初始数据副本
    originalFormData.value = JSON.parse(JSON.stringify(userData));

    console.log('Initial data loaded:', originalFormData.value);
  } else {
    ElMessage.warning("用户信息未加载，请稍后重试或重新登录。");
  }
});

// 组件销毁时清理头像预览 URL，防止内存泄漏
onUnmounted(() => {
  if (avatarObjectURL.value) {
    URL.revokeObjectURL(avatarObjectURL.value);
  }
});

/**
 * 检查表单是否有未保存的修改
 */
const isFormDirty = computed(() => {
  if (!originalFormData.value.userId) return false;

  const original = originalFormData.value;
  const current = formData.value;

  // 标准化比较函数 - 处理 null/undefined/空字符串的情况
  const normalizeValue = (value) => {
    if (value === null || value === undefined) return '';
    return String(value);
  };

  const normalizeGender = (value) => {
    if (value === null || value === undefined) return null;
    return Number(value);
  };

  // 比较各个字段
  const genderChanged = normalizeGender(original.gender) !== normalizeGender(current.gender);
  const mobileChanged = normalizeValue(original.mobile) !== normalizeValue(current.mobile);
  const emailChanged = normalizeValue(original.email) !== normalizeValue(current.email);
  const avatarChanged = current.avatarFile !== null;

  console.log('Form dirty check:', {
    genderChanged,
    mobileChanged,
    emailChanged,
    avatarChanged,
    original: {
      gender: original.gender,
      mobile: original.mobile,
      email: original.email
    },
    current: {
      gender: current.gender,
      mobile: current.mobile,
      email: current.email,
      hasAvatarFile: current.avatarFile !== null
    }
  });

  return genderChanged || mobileChanged || emailChanged || avatarChanged;
});

// 使用导航守卫，在离开页面时检查是否有未保存的修改
onBeforeRouteLeave((to, from, next) => {
  if (isFormDirty.value) {
    ElMessageBox.confirm(
      '您有未保存的修改，是否要保存？',
      '提示',
      {
        distinguishCancelAndClose: true,
        confirmButtonText: '保存并离开',
        cancelButtonText: '放弃修改',
        type: 'warning',
      }
    )
    .then(() => {
      // 用户选择保存
      submitForm().then(() => {
        next(); // 保存成功后放行
      }).catch(() => {
        next(false); // 保存失败，阻止导航
      });
    })
    .catch((action) => {
      if (action === 'cancel') {
        next(); // 用户选择放弃修改，直接放行
      } else {
        next(false); // 用户点击了关闭按钮，阻止导航
      }
    });
  } else {
    next(); // 没有修改，直接放行
  }
});

/**
 * 处理头像文件变更
 * @param {File} file - ElUpload 提供的文件对象
 */
const handleAvatarChange = (file) => {
  // 清理之前的头像预览 URL
  if (avatarObjectURL.value) {
    URL.revokeObjectURL(avatarObjectURL.value);
  }

  formData.value.avatarFile = file.raw;
  avatarObjectURL.value = URL.createObjectURL(file.raw);
  formData.value.avatar = avatarObjectURL.value;
};

/**
 * 提交表单进行保存
 */
const submitForm = async () => {
  const userId = userStore.userInfo.userId;
  if (!userId) {
    ElMessage.error("用户信息不完整，无法更新");
    return false;
  }

  // 创建一个 FormData 对象来封装所有数据
  const updateFormData = new FormData();

  // 添加需要更新的字段
  if (formData.value.gender !== undefined && formData.value.gender !== null) {
    updateFormData.append("gender", formData.value.gender);
  }
  if (formData.value.mobile) {
    updateFormData.append("mobile", formData.value.mobile);
  }
  if (formData.value.email) {
    updateFormData.append("email", formData.value.email);
  }
  // 仅在有新头像文件时添加
  if (formData.value.avatarFile) {
    updateFormData.append("avatarFile", formData.value.avatarFile);
  }

  try {
    // 调用更新 API，传递 userId 和 FormData
    const response = await updateUser(userId, updateFormData);
    if (response.data.code === 1) {
      ElMessage.success("资料更新成功");

      // 更新 userStore 中的用户信息
      Object.assign(userStore.userInfo, {
        gender: formData.value.gender,
        mobile: formData.value.mobile,
        email: formData.value.email,
        // 如果后端返回了新的头像URL，使用后端返回的
        avatar: response.data.data?.avatar || formData.value.avatar
      });

      localStorage.setItem('userInfo', JSON.stringify(userStore.userInfo));

      // 重要：重置 avatarFile 并更新 originalFormData
      formData.value.avatarFile = null;
      originalFormData.value = JSON.parse(JSON.stringify(formData.value));

      console.log('Data saved, updated originalFormData:', originalFormData.value);

      router.push('/person_message');
      return true;
    } else {
      ElMessage.error(response.msg || "资料更新失败，请重试");
      return false;
    }
  } catch (error) {
    console.error("更新用户信息失败:", error);
    ElMessage.error("网络错误，请稍后重试");
    return false;
  }
};

/**
 * 重置表单到初始状态（可选功能）
 */
const resetForm = () => {
  // 清理头像预览 URL
  if (avatarObjectURL.value) {
    URL.revokeObjectURL(avatarObjectURL.value);
    avatarObjectURL.value = null;
  }

  // 重置表单数据
  formData.value = JSON.parse(JSON.stringify(originalFormData.value));
  formData.value.avatarFile = null;
};
</script>

<style scoped>
.edit-profile-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 30px;
}

.edit-content {
  padding: 20px;
}

.avatar-edit-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-avatar-placeholder {
  font-size: 60px;
  color: #ccc;
}

.avatar-uploader .el-upload {
  display: block;
}

.el-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.el-button {
  width: 100%;
}
</style>